﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DGSFramework;
using System.Web.Security;
using System.Xml.Linq;

namespace Framework.WebmasterTool.Memberships
{
    public partial class CreateGroup : System.Web.UI.Page
    {
        DGSFrameworkEntities entity = new DGSFrameworkEntities();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CheckPermission();
                LoadRoleDetails();
            }
        }

        public void CheckPermission()
        {
            MembershipUser someUser = Membership.GetUser();
            if (someUser == null)
            {
                Response.Redirect(Globals.ApplicationPath + "LoginAdmin/Default.aspx");
            }
            bool flag = false;
            var user = entity.aspnet_Users.Where(us => us.UserName == someUser.UserName).FirstOrDefault();
            user.aspnet_Roles.Load();
            var rolesForUser = user.aspnet_Roles.ToList();
            foreach (var item in rolesForUser)
            {
                var permission = entity.udv_Permissions.Where(ps => ps.RoleId == item.RoleId).FirstOrDefault();
                if (permission.ManagerUser.Value == true)
                {
                    flag = true;
                }
            }
            if (flag == false)
            {
                lblPermissionMessage.Visible = true;
                Panel1.Visible = false;
            }
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            Response.Redirect("ManagerGroups.aspx");
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (Request.QueryString["RoleID"] != null)
            {
                Guid roleID = new Guid(Request.QueryString["RoleID"].ToString());
                var role = entity.aspnet_Roles.Where(rl => rl.RoleId == roleID).FirstOrDefault();
                if (role != null)
                {
                    try
                    {
                        string oldRoleName = role.RoleName;
                        role.RoleName = txtRole.Text.Trim();
                        role.LoweredRoleName = txtRole.Text.Trim().ToLower();
                        role.Description = txtDescription.Text;
                        entity.SaveChanges();
                        var permission = entity.udv_Permissions.Where(ps => ps.RoleId == role.RoleId).FirstOrDefault();
                        permission.Advertising = chkAdvertising.Checked;
                        permission.Article = chkArticle.Checked;
                        permission.Category = chkCategory.Checked;
                        permission.Comment = chkComment.Checked;
                        permission.Company = chkCompany.Checked;
                        permission.Contact = chkContact.Checked;
                        permission.DownloadFile = chkDownloadFile.Checked;
                        permission.GalleryImage = chkGalleryImage.Checked;
                        permission.GalleryVideo = chkGallleryVideo.Checked;
                        permission.GalleryPhoto = chkGalleryPhoto.Checked;
                        permission.Mailserver = chkMailServer.Checked;
                        permission.ManagerUser = chkManagerUser.Checked;
                        permission.LogSystem = chkLogSystem.Checked;
                        permission.Report = chkReport.Checked;
                        permission.Tag = chkTag.Checked;
                        permission.NewsLetter = chkNewsLetter.Checked;
                        permission.Product = chkProduct.Checked;
                        permission.RewriteURL = chkRewriteURL.Checked;
                        permission.SlideShow = chkSlideShow.Checked;
                        permission.SupportOnline = chkSupportOnline.Checked;
                        permission.Vote = chkVote.Checked;
                        permission.Watermark = chkWatermark.Checked;
                        permission.Weblink = chkWeblink.Checked;
                        permission.WebmasterTool = chkWebmasterTool.Checked;
                        entity.SaveChanges();
                        XDocument xDocWebconfig = XDocument.Load(HttpContext.Current.Server.MapPath("\\WebmasterTool\\web.config"));
                        XElement xEAllowRoles = xDocWebconfig.Descendants("authorization").Descendants("allow").Where(ra => ra.Attribute("roles") != null).FirstOrDefault();
                        XElement xEDenyRoles = xDocWebconfig.Descendants("authorization").Descendants("deny").Where(ra => ra.Attribute("roles") != null).FirstOrDefault();
                        if (chkWebmasterTool.Checked == true)
                        {
                            if (xEAllowRoles.Attribute("roles").Value.Contains(oldRoleName))
                            {
                                xEAllowRoles.Attribute("roles").Value = xEAllowRoles.Attribute("roles").Value.Replace(oldRoleName, role.RoleName);
                                xEAllowRoles.Attribute("roles").Value = Globals.RemoveMultipeString(xEAllowRoles.Attribute("roles").Value, ",");
                            }
                            else
                            {
                                xEAllowRoles.Attribute("roles").Value += role.RoleName + ",";
                                xEAllowRoles.Attribute("roles").Value = Globals.RemoveMultipeString(xEAllowRoles.Attribute("roles").Value, ",");
                            }
                            if (xEDenyRoles.Attribute("roles").Value.Contains(oldRoleName))
                            {
                                xEDenyRoles.Attribute("roles").Value = xEDenyRoles.Attribute("roles").Value.Replace(oldRoleName, "");
                                xEDenyRoles.Attribute("roles").Value = Globals.RemoveMultipeString(xEDenyRoles.Attribute("roles").Value, ",");
                            }
                        }
                        else
                        {
                            if (xEAllowRoles.Attribute("roles").Value.Contains(oldRoleName))
                            {
                                xEAllowRoles.Attribute("roles").Value = xEAllowRoles.Attribute("roles").Value.Replace(oldRoleName, "");
                                xEAllowRoles.Attribute("roles").Value = Globals.RemoveMultipeString(xEAllowRoles.Attribute("roles").Value, ",");
                            }
                            if (xEDenyRoles.Attribute("roles").Value.Contains(oldRoleName))
                            {
                                xEDenyRoles.Attribute("roles").Value = xEDenyRoles.Attribute("roles").Value.Replace(oldRoleName, role.RoleName);
                                xEDenyRoles.Attribute("roles").Value = Globals.RemoveMultipeString(xEDenyRoles.Attribute("roles").Value, ",");
                            }
                            else
                            {
                                xEDenyRoles.Attribute("roles").Value += role.RoleName + ",";
                                xEDenyRoles.Attribute("roles").Value = Globals.RemoveMultipeString(xEDenyRoles.Attribute("roles").Value, ",");
                            }
                        }
                        xDocWebconfig.Save(HttpContext.Current.Server.MapPath("\\WebmasterTool\\web.config"));

                        //create db log
                        CreateDBLog(null, null, TypeAction.Update, "Cập nhật nhóm thành viên: " + oldRoleName + " - " + role.RoleName, role.Description, "", "", "",
                                "", "", "", "");

                        Response.Redirect("ManagerGroups.aspx", false);
                    }
                    catch
                    {
                        lblMsg.Text = "Nhóm này đã tồn tại trong hệ thống";
                    }
                }
                else
                {
                    Response.Redirect("ManagerGroups.aspx");
                }
            }
            else
            {
                if (!Roles.RoleExists(txtRole.Text.Trim()))
                {
                    Roles.CreateRole(txtRole.Text.Trim());
                    var newRole = entity.aspnet_Roles.Where(rl => rl.RoleName == txtRole.Text.Trim()).FirstOrDefault();
                    newRole.Description = txtDescription.Text;
                    entity.SaveChanges();
                    udv_Permissions newPermission = new udv_Permissions();
                    newPermission.aspnet_Roles = newRole;
                    newPermission.Advertising = chkAdvertising.Checked;
                    newPermission.Article = chkArticle.Checked;
                    newPermission.Category = chkCategory.Checked;
                    newPermission.Comment = chkComment.Checked;
                    newPermission.Company = chkCompany.Checked;
                    newPermission.Contact = chkContact.Checked;
                    newPermission.DownloadFile = chkDownloadFile.Checked;
                    newPermission.GalleryImage = chkGalleryImage.Checked;
                    newPermission.GalleryVideo = chkGallleryVideo.Checked;
                    newPermission.GalleryPhoto = chkGalleryPhoto.Checked;
                    newPermission.Mailserver = chkMailServer.Checked;
                    newPermission.ManagerUser = chkManagerUser.Checked;
                    newPermission.LogSystem = chkLogSystem.Checked;
                    newPermission.Report = chkReport.Checked;
                    newPermission.Tag = chkTag.Checked;
                    newPermission.NewsLetter = chkNewsLetter.Checked;
                    newPermission.Product = chkProduct.Checked;
                    newPermission.RewriteURL = chkRewriteURL.Checked;
                    newPermission.SlideShow = chkSlideShow.Checked;
                    newPermission.SupportOnline = chkSupportOnline.Checked;
                    newPermission.Vote = chkVote.Checked;
                    newPermission.Watermark = chkWatermark.Checked;
                    newPermission.Weblink = chkWeblink.Checked;
                    newPermission.WebmasterTool = chkWebmasterTool.Checked;
                    entity.SaveChanges();
                    XDocument xDocWebconfig = XDocument.Load(HttpContext.Current.Server.MapPath("\\WebmasterTool\\web.config"));
                    XElement xEAllowRoles = xDocWebconfig.Descendants("authorization").Descendants("allow").Where(ra => ra.Attribute("roles") != null).FirstOrDefault();
                    XElement xEDenyRoles = xDocWebconfig.Descendants("authorization").Descendants("deny").Where(ra => ra.Attribute("roles") != null).FirstOrDefault();
                    if (chkWebmasterTool.Checked == true)
                    {
                        xEAllowRoles.Attribute("roles").Value += newRole.RoleName + ",";
                        xEAllowRoles.Attribute("roles").Value = Globals.RemoveMultipeString(xEAllowRoles.Attribute("roles").Value, ",");
                    }
                    else
                    {
                        xEDenyRoles.Attribute("roles").Value += newRole.RoleName + ",";
                        xEDenyRoles.Attribute("roles").Value = Globals.RemoveMultipeString(xEDenyRoles.Attribute("roles").Value, ",");
                    }
                    xDocWebconfig.Save(HttpContext.Current.Server.MapPath("\\WebmasterTool\\web.config"));

                    //create db log
                    CreateDBLog(null, null, TypeAction.Insert, "Thêm nhóm thành viên: " + newRole.RoleName, newRole.Description, "", "", "",
                            "", "", "", "");

                    Response.Redirect("ManagerGroups.aspx");
                }
                else
                {
                    lblMsg.Text = "Nhóm này đã tồn tại trong hệ thống";
                }
            }
        }

        public void LoadRoleDetails()
        {
            MembershipUser currentUser = Membership.GetUser();
            if (Request.QueryString["RoleID"] != null)
            {
                string strAdministrator = "Super Administrator";
                Guid roleID = new Guid();
                try
                {
                    roleID = new Guid(Request.QueryString["RoleID"].ToString());
                }
                catch
                {
                    Response.Redirect("ManagerGroups.aspx");
                }
                var role = entity.aspnet_Roles.Where(rl => rl.RoleId == roleID).FirstOrDefault();
                try
                {
                    
                    if (role != null)
                    {
                        if (Roles.IsUserInRole(currentUser.UserName, strAdministrator) == false && role.RoleName == strAdministrator)
                        {
                            Response.Redirect("ManagerGroups.aspx");
                        }

                        txtRole.Text = role.RoleName;
                        txtDescription.Text = role.Description;
                        var permission = entity.udv_Permissions.Where(ps => ps.RoleId == role.RoleId).FirstOrDefault();
                        chkAdvertising.Checked = permission.Advertising.Value;
                        chkArticle.Checked = permission.Article.Value;
                        chkCategory.Checked = permission.Category.Value;
                        chkComment.Checked = permission.Comment.Value;
                        chkCompany.Checked = permission.Company.Value;
                        chkContact.Checked = permission.Contact.Value;
                        chkDownloadFile.Checked = permission.DownloadFile.Value;
                        chkGalleryImage.Checked = permission.GalleryImage.Value;
                        chkGallleryVideo.Checked = permission.GalleryVideo.Value;
                        chkGalleryPhoto.Checked = permission.GalleryPhoto.Value;
                        chkMailServer.Checked = permission.Mailserver.Value;
                        chkManagerUser.Checked = permission.ManagerUser.Value;
                        chkLogSystem.Checked = permission.LogSystem.Value;
                        chkReport.Checked = permission.Report.Value;
                        chkTag.Checked = permission.Tag.Value;
                        chkNewsLetter.Checked = permission.NewsLetter.Value;
                        chkProduct.Checked = permission.Product.Value;
                        chkRewriteURL.Checked = permission.RewriteURL.Value;
                        chkSlideShow.Checked = permission.SlideShow.Value;
                        chkSupportOnline.Checked = permission.SupportOnline.Value;
                        chkVote.Checked = permission.Vote.Value;
                        chkWatermark.Checked = permission.Watermark.Value;
                        chkWeblink.Checked = permission.Weblink.Value;
                        chkWebmasterTool.Checked = permission.WebmasterTool.Value;
                        if (Roles.IsUserInRole(currentUser.UserName, strAdministrator) == true)
                        {
                            txtRole.Enabled = false;
                        }
                        else if (role.RoleName == "Administrator")
                        {
                            txtRole.Enabled = false;
                            chkAdvertising.Enabled = false;
                            chkArticle.Enabled = false;
                            chkCategory.Enabled = false;
                            chkComment.Enabled = false;
                            chkCompany.Enabled = false;
                            chkContact.Enabled = false;
                            chkDownloadFile.Enabled = false;
                            chkGalleryImage.Enabled = false;
                            chkGallleryVideo.Enabled = false;
                            chkGalleryPhoto.Enabled = false;
                            chkMailServer.Enabled = false;
                            chkManagerUser.Enabled = false;
                            chkLogSystem.Enabled = false;
                            chkReport.Enabled = false;
                            chkTag.Enabled = false;
                            chkNewsLetter.Enabled = false;
                            chkProduct.Enabled = false;
                            chkRewriteURL.Enabled = false;
                            chkSlideShow.Enabled = false;
                            chkSupportOnline.Enabled = false;
                            chkVote.Enabled = false;
                            chkWatermark.Enabled = false;
                            chkWeblink.Enabled = false;
                            chkWebmasterTool.Enabled = false;
                        }
                        else if (role.RoleName == "User")
                        {
                            txtRole.Enabled = false;
                        }
                    }
                    else
                    {
                        Response.Redirect("ManagerGroups.aspx", false);
                    }
                }
                catch
                {
                    Response.Redirect("ManagerGroups.aspx");
                }
            }
            LoadModule(currentUser);
        }

        public void LoadModule(MembershipUser currentUser)
        {
            string strAdministrator = "Super Administrator";
            var roleSupperAdmin = entity.udv_Permissions.Where(rl => rl.aspnet_Roles.RoleName == strAdministrator).FirstOrDefault();
            if (Roles.IsUserInRole(currentUser.UserName, strAdministrator) == false)
            {
                if (roleSupperAdmin.Advertising.Value == false)
                {
                    chkAdvertising.Visible = false;
                }
                if (roleSupperAdmin.Article.Value == false)
                {
                    chkArticle.Visible = false;
                }
                if (roleSupperAdmin.Category.Value == false)
                {
                    chkCategory.Visible = false;
                }
                if (roleSupperAdmin.Comment == false)
                {
                    chkComment.Visible = false;
                }
                if (roleSupperAdmin.Company.Value == false)
                {
                    chkCompany.Visible = false;
                }
                if (roleSupperAdmin.Contact.Value == false)
                {
                    chkContact.Visible = false;
                }
                if (roleSupperAdmin.DownloadFile.Value == false)
                {
                    chkDownloadFile.Visible = false;
                }
                if (roleSupperAdmin.GalleryImage.Value == false)
                {
                    chkGalleryImage.Visible = false;
                }
                if (roleSupperAdmin.GalleryPhoto.Value == false)
                {
                    chkGalleryPhoto.Visible = false;
                }
                if (roleSupperAdmin.GalleryVideo.Value == false)
                {
                    chkGallleryVideo.Visible = false;
                }
                if (roleSupperAdmin.LogSystem.Value == false)
                {
                    chkLogSystem.Visible = false;
                }
                if (roleSupperAdmin.Mailserver.Value == false)
                {
                    chkMailServer.Visible = false;
                }
                if (roleSupperAdmin.ManagerUser.Value == false)
                {
                    chkManagerUser.Visible = false;
                }
                if (roleSupperAdmin.NewsLetter.Value == false)
                {
                    chkNewsLetter.Visible = false;
                }
                if (roleSupperAdmin.Product.Value == false)
                {
                    chkProduct.Visible = false;
                }
                if (roleSupperAdmin.Report.Value == false)
                {
                    chkReport.Visible = false;
                }
                if (roleSupperAdmin.RewriteURL.Value == false)
                {
                    chkRewriteURL.Visible = false;
                }
                if (roleSupperAdmin.SlideShow.Value == false)
                {
                    chkSlideShow.Visible = false;
                }
                if (roleSupperAdmin.SupportOnline.Value == false)
                {
                    chkSupportOnline.Visible = false;
                }
                if (roleSupperAdmin.Tag.Value == false)
                {
                    chkTag.Visible = false;
                }
                if (roleSupperAdmin.Vote.Value == false)
                {
                    chkVote.Visible = false;
                }
                if (roleSupperAdmin.Watermark.Value == false)
                {
                    chkWatermark.Visible = false;
                }
                if (roleSupperAdmin.Weblink.Value == false)
                {
                    chkWeblink.Visible = false;
                }
                if (roleSupperAdmin.WebmasterTool == false)
                {
                    chkWebmasterTool.Visible = false;
                }
            }
        }

        public void CreateDBLog(int? postID, int? postCateID, TypeAction typeAction, string title, string _abstract, string description,
        string releaseDate, string expireDate, string isApproved, string statusID, string metaDescription, string metaKeywords)
        {
            udv_Log log = new udv_Log();
            log.PostID = postID;
            log.PostCateID = postCateID;
            log.TypeAction = (int)typeAction;
            log.Title = title;
            log.Abstract = _abstract;
            log.Description = description;
            log.ReleaseDate = releaseDate;
            log.ExpireDate = expireDate;
            log.IsApproved = isApproved;
            log.StatusID = statusID;
            log.MetaDescription = metaDescription;
            log.MetaKeywords = metaKeywords;
            log.ActionedDate = DateTime.Now;
            log.ActionBy = Membership.GetUser().UserName;
            log.IpAdress = Globals.GetClientIPAddress();

            entity.AddToudv_Log(log);
            entity.SaveChanges();
        }
    }
}